package test.jfreechart;

import java.awt.Color;
import java.text.SimpleDateFormat;
import java.util.Random;
import java.util.Map.Entry;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.time.Second;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
import org.jfree.experimental.chart.swt.ChartComposite;
import org.jfree.ui.RectangleInsets;

/**
 * chaonan
 * 动态图表例
 */
public class SWTTimeSeries
{


    private static  TimeSeriesCollection dataset = new TimeSeriesCollection();
    private static MyMap dataMp=new MyMap();
    private static MyMap dataMp1=new MyMap();
    private static  TimeSeries s1 = new TimeSeries("cpu", Second.class);
    private static  TimeSeries s2 = new TimeSeries("Ram", Second.class);


     /**
     * Creates a chart.
     * 
     * @param dataset  a dataset.
     * 
     * @return A chart.
     */
    private static JFreeChart createChart(XYDataset dataset) {

        JFreeChart chart = ChartFactory.createTimeSeriesChart(
            "resourceuse",  // title
            "time",             // x-axis label
            "use",   // y-axis label
            dataset,            // data
            true,               // create legend?
            true,               // generate tooltips?
            false               // generate URLs?
        );

        chart.setBackgroundPaint(Color.white);


        XYPlot plot = (XYPlot) chart.getPlot();
        plot.setBackgroundPaint(Color.lightGray);
        plot.setDomainGridlinePaint(Color.white);
        plot.setRangeGridlinePaint(Color.white);
        plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
        plot.setDomainCrosshairVisible(true);
        plot.setRangeCrosshairVisible(true);
        plot.getRangeAxis().setUpperBound(100);  
        XYItemRenderer r = plot.getRenderer();
        if (r instanceof XYLineAndShapeRenderer) {
            XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
            renderer.setBaseShapesVisible(true);
            renderer.setBaseShapesFilled(true);
        }

        DateAxis axis = (DateAxis) plot.getDomainAxis();
        axis.setDateFormatOverride(new SimpleDateFormat("mm:ss"));

        return chart;

    }

    /**
     * Creates a dataset, consisting of two series of monthly data.
     *
     * @return The dataset.
     */
    private static XYDataset addToDataset() {//更新数据
        Random r=new Random();//随机数

        dataMp.put(new Second(),20+ r.nextInt(50));
        dataMp1.put(new Second(), 20+ r.nextInt(50));
        //cpuList.add(cpuuse);
        s1.clear();
        s2.clear();
        for(Entry<Second,Integer> e:dataMp.entrySet() ){
            s1.add(e.getKey(),e.getValue());
        }
        for(Entry<Second,Integer> e:dataMp1.entrySet() ){
            s2.add(e.getKey(),e.getValue());
        }

        dataset.removeAllSeries();
        dataset.addSeries(s1);
        dataset.addSeries(s2);

        return dataset;
    }


    /**
     * Starting point for the demonstration application.
     *
     * @param args  ignored.
     */
    public static void main(String[] args) {



        final JFreeChart chart = createChart(dataset);
        final Display display = new Display();
        Shell shlCpu = new Shell(display);
        shlCpu.setSize(655, 487);
        shlCpu.setText("cpu\u4F7F\u7528\u60C5\u51B5");
        shlCpu.setLayout(new FillLayout(SWT.HORIZONTAL));

        SashForm sashForm = new SashForm(shlCpu, SWT.NONE);

        Composite composite = new Composite(sashForm, SWT.NONE);

        Button button = new Button(composite, SWT.NONE);
        button.addSelectionListener(new SelectionAdapter() {

            public void widgetSelected(SelectionEvent e) {
                new Thread(new Runnable() {

                    public void run() {
                        while (true) {
                            try {
                                Thread.sleep(2000);
                            } catch (InterruptedException e) {

                                e.printStackTrace();
                            }
                            Display.getDefault().asyncExec(new Runnable() {

                                public void run() {
//                                  GetLinuxInfo service = new GetLinuxInfoImpl();
//                                  InfoData dataInfo = null;
//                                  try {
////                                        dataInfo = service.getInfo();
//                                  } catch (Exception e) {
//                                      // TODO Auto-generated catch block
//                                      e.printStackTrace();
//                                  }
                                    addToDataset();

                                    //System.out.println(dataInfo.getCpu().getCpuTotalUse());
                                }

                            });

                        }

                    }
                }).start();
            }
        });
        button.setBounds(27, 44, 98, 30);
        button.setText("启动");

        Composite composite_1 = new Composite(sashForm, SWT.NONE);
        composite_1.setLayout(new FillLayout(SWT.HORIZONTAL));
        ChartComposite frame = new ChartComposite(composite_1, SWT.NONE, chart, true);
        frame.setDisplayToolTips(true);
        frame.setHorizontalAxisTrace(false);
        frame.setVerticalAxisTrace(false);
        sashForm.setWeights(new int[] {171, 287});
        shlCpu.open();


        while (!shlCpu.isDisposed()) {
            if (!display.readAndDispatch())
                display.sleep();
        }
    }
}
